package com.oocl.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import com.oocl.communicator.Receiver;
import com.oocl.communicator.Sender;
import com.oocl.communicator.impl.ReceiverImpl;
import com.oocl.communicator.impl.SenderImpl;
import com.oocl.constant.LogLevel;
import com.oocl.constant.ProtocolType;
import com.oocl.parser.ProtocolParser;
import com.oocl.parser.impl.ProtocolParseImpl;
import com.oocl.pojo.Protocol;
import com.oocl.util.ConsoleLogUtil;
import com.oocl.util.ResourceCloser;

/**
 * 用户服务子线程
 * @author MAIKE 
 *
 */
public class UserThread extends Thread {
	private Socket socket;
	private Receiver receiver;
	private ProtocolParser parser;
	private BufferedReader in;
	private PrintWriter out;
	private Sender sender;
	private boolean isRunning = true;
	
	public UserThread(Socket socket) {
		this.socket = socket;
	}
	
	@Override
	public void run() {
		
		try {
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(socket.getOutputStream());
			sender = new SenderImpl(out);
			receiver = new ReceiverImpl();
			parser = new ProtocolParseImpl(sender);
			
			while(isRunning){
				if(socket.isClosed()){
					break;
				}
				Protocol pro = receiver.receive(in);
				ConsoleLogUtil.log("server receive a Protocol package! "+pro, LogLevel.INFO);
				if(null==pro){
					continue;
				}
				switch (pro.getType()) {
				case ProtocolType.LOAD_USERS:
					parser.parseLoadUsers(pro,this);
					break;
				case ProtocolType.LAYOUT:
					parser.parseLoyout(pro,this);
					break;
				case ProtocolType.PRIVATE_TALK:
					parser.parsePrivateTalk(pro);
					break;
				case ProtocolType.GROUPE_TALK:
					parser.parseGroupTalk(pro);
					break;
				case ProtocolType.GROUP_SHAKE:
					parser.parseGroupShake(pro);
					break;
				case ProtocolType.PRIVATE_SHAKE:
					parser.parsePrivateShake(pro);
					break;
				default:
					break;
				}
			}
		} catch (IOException e) {
			ConsoleLogUtil.log("Server IO Exception! "+e.getMessage(), LogLevel.ERROR);
			ResourceCloser.release(out, in, null, null);
//			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			ConsoleLogUtil.log("Server ClassNotFoundException, Can not read Object!"+e.getMessage(), LogLevel.ERROR);
			ResourceCloser.release(out, in, null, null);
//			e.printStackTrace();
		} finally {
			ResourceCloser.release(out, in, null, null);
		}
	}

	public Sender getSender() {
		return sender;
	}

	public void setRunning(boolean isRunning) {
		this.isRunning = isRunning;
	}

	public Socket getSocket() {
		return socket;
	}

}
